package com.base.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

/**
 * 文件加密工具类
 * 
 * @author wj
 * 
 */
public class FileDESUtil {

	private static Cipher encryptCipher;
	private static Cipher decryptCipher;

	private static final String KEY = "kxd";

	static {
		try {
			Key key = getKey(KEY.getBytes());
			encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);
			decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static Key getKey(byte[] arrBTmp) throws Exception {
		byte[] arrB = new byte[8];

		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
		return key;
	}

	/**
	 * 加密
	 * 
	 * @param is
	 * @param out
	 * @throws Exception
	 */
	public static void encrypt(InputStream is, OutputStream out) throws Exception {
		CipherInputStream cis = new CipherInputStream(is, encryptCipher);
		byte[] buffer = new byte[4096];
		int r;
		while ((r = cis.read(buffer)) > 0) {
			out.write(buffer, 0, r);
		}
		cis.close();

	}

	/**
	 * 解密
	 * 
	 * @param is
	 * @param out
	 * @throws Exception
	 */
	public static void decrypt(InputStream is, OutputStream out) throws Exception {
		CipherOutputStream cos = new CipherOutputStream(out, decryptCipher);
		byte[] buffer = new byte[4096];
		int r;
		while ((r = is.read(buffer)) >= 0) {
			cos.write(buffer, 0, r);
		}
		cos.close();
	}

}